using System;
using Microsoft.WindowsAzure.StorageClient;

namespace Microsoft.WindowsAzure.Accelerator
{
    /// <summary>
    /// Extensions to the CloudBlob class, which represents a Windows Azure blob.
    /// </summary>
    public static class CloudBlobExtensions
    {
        /// <summary>
        /// Test for the existence of a blob.
        /// </summary>
        /// <param name="blob">The blob.</param>
        /// <returns></returns>
        public static Boolean Exists(this CloudBlob blob)
        {
            return CloudBlobExtensions.Exists(blob, null);
        }

        /// <summary>
        /// Test for the existence of a blob using the additional blob request options.  This allows for bringing back additional metadata or performing
        /// enhanced decision logic based on a single request to the storage service.
        /// </summary>
        /// <param name="blob">The blob.</param>
        /// <param name="options">The options for the request.</param>
        /// <returns></returns>
        public static Boolean Exists(this CloudBlob blob, BlobRequestOptions options)
        {
            try
            {
                if (options != null)
                {
                    blob.FetchAttributes(options);
                }
                else
                {
                    blob.FetchAttributes();
                }
                return true;
            }
            catch (StorageClientException e)
            {
                if (e.ErrorCode == StorageErrorCode.ResourceNotFound || e.ErrorCode == StorageErrorCode.ContainerNotFound || e.ErrorCode == StorageErrorCode.BlobNotFound)
                {
                    return false;
                }
                throw;
            }
        }
    }
}